package com.zhugang.week13.linkedlist;

/**
 * @program algorithms
 * @description: deleteDuplicates
 * @author: chanzhugang
 * @create: 2022/10/23 21:25
 */
public class DeleteDuplicates {

    /**
     * 83 删除排序链表中的重复元素
     * https://leetcode.cn/problems/remove-duplicates-from-sorted-list/
     *
     * @param head
     * @return
     */
    public ListNode deleteDuplicates(ListNode head) {
        // 和移除链表元素代码几乎一样
        // 通用解法：虚拟头节点 + tail，把解法讲出来
        // 当前节点不等于尾节点，就添加
        ListNode newNode = new ListNode(-101, null);
        ListNode tail = newNode;
        ListNode p = head;
        while (p != null) {
            ListNode next = p.next;
            if (p.val != tail.val) {
                p.next = null;
                // 尾插
                tail.next = p;
                tail = p;
            }
            p = next;
        }
        return newNode.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}